﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Facebook_Graph_Toolkit.Helpers {
    /// <summary>
    /// Provides methods to manage a Facebook Application
    /// </summary>
    public class AppManager {
        /// <summary>
        /// Gets the App Access Token of this app using the configuration stored in web.config
        /// </summary>
        /// <returns>App Access Token</returns>
        public static string GetAppAccessToken() {
            FacebookGraphToolkitConfiguration Config = Helpers.Common.GetAppConfig(true);
            if (string.IsNullOrEmpty(Config._FacebookAppID)) throw new ArgumentNullException("FacebookAppID","Value not found in web.config .");
            if (string.IsNullOrEmpty(Config._FacebookAppSecret)) throw new ArgumentNullException("FacebookAppSecret", "Value not found in web.config .");
            return GetAppAccessToken(Config._FacebookAppID, Config._FacebookAppSecret);
        }
        /// <summary>
        /// Gets the App Access Token of the specified Facebook Application
        /// </summary>
        /// <param name="FacebookAppID">Application ID</param>
        /// <param name="FacebookAppSecret">Application Secret</param>
        /// <returns>App Access Token</returns>
        public static string GetAppAccessToken(string FacebookAppID, string FacebookAppSecret) {
            if (string.IsNullOrEmpty(FacebookAppID)) throw new ArgumentNullException("FacebookAppID");
            if (string.IsNullOrEmpty(FacebookAppSecret)) throw new ArgumentNullException("FacebookAppSecret");
            string url = string.Format("https://graph.facebook.com/oauth/access_token?client_id={0}&client_secret={1}&grant_type=client_credentials", FacebookAppID, FacebookAppSecret);
            string response = WebResponseHelper.GetWebResponse(url);
            if (response.IndexOf("access_token=") == -1) throw new FacebookException("Unknown response from Facebook.");
            string[] pair = response.Split('=');
            return pair[1];
        }
    }
}
